var express = require('express');
var router = express.Router();
var Users = require('../models/users.js');
//加密
var crypto = require('crypto');
function md5 (text) {
    return crypto.createHash('md5').update(text).digest('hex');
};


// 登录
router.get('/login', function(req, res, next) {
    var _returnurl = req.query.returnurl;
    res.render('admin/login',{
        "returnurl":_returnurl
    });
});
router.post('/login', function(req, res, next) {
    var _users= {};
    for(var i in req.body){
        _users[i] = req.body[i];
    }
    //加密密码
    _users["password"] = md5(_users.password);
    var obj = new Users();
    obj.getOne(_users.username,function(err,users){
       if(err){
           res.render('admin/login',{
               msg:{error:"网络出错"}
           });
       }else if(!users[0]){
           res.render('admin/login',{
               msg:{error:"用户不存在"}
           });
       }else if(users[0].password!=_users.password){
           res.render('admin/login',{
               msg:{error:"密码错误"}
           });
       }else{
           //设session
            req.session.user = users[0];
           res.redirect("/admin/index");
       }
    });

});

//退出
router.get('/logout', function(req, res, next) {
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:"+JSON.stringify(req.session.user));
    req.session.user=null;
    res.redirect("/admin/login");
});

//首页
router.get('/index', function(req, res, next) {
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:"+JSON.stringify(req.session.user));
    res.render('admin/index',{
        user:req.session.user
    });
});

//for update file test
router.get('/temp/upload', function(req, res, next) {
    res.render('admin/temp/upload');
});
router.post('/temp/upload',  function(req, res, next) {
    console.log( req.files.phote.path);//图片保存路径
   res.send(req.file);
});


module.exports = router;